<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column' }">
      <!-- <PatientList @select="onSelectPatient" /> -->
      <PatientListDrawer
        :patient-list="patientList"
        :border-bottom="false"
        :selected-item="selectedItem"
        :loading="listLoading"
        @select="selectPatient"
        @refresh="getInpRecordList"
      >
        <template #search>
          <div class="w-full px-2">
            <SelectArea
              v-model:value="searchParams.bqid"
              use-cache
              class="w-full"
              post-url
              :post-params="{ wardTypeCodes: ['QYLB001', 'QYLB002'] }"
              @change="getInpRecordList"
            />
          </div>
        </template>
        <template #tabRadio>
          <div class="p-2 w-full -mt-2 border-b">
            <a-input-search
              v-model:value="searchParams.zjm"
              class="w-full"
              placeholder="姓名/助记码/床位号"
              @search="getInpRecordList()"
              @change="onSearch()"
            />
          </div>
        </template>
      </PatientListDrawer>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="selectedItem">
        <template #prefix>
          <div class="text-2xl pr-4 text-primary font-semibold">{{ selectedItem.bedCode || ' - ' }}床</div>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="住院科室" :width="160" :value="selectedItem.ksmc" />
            <LabelValue label="住院号" :width="220" :value="selectedItem.admissionCode" />
            <!-- <LabelValue label="过敏史" :width="200" :value="selectedItem.brGms" /> -->
            <AllergyHistory :width="200" :value="selectedItem.brGms" :patient-info="selectedItem" @success="(e) => (selectedItem.brGms = e)" />
            <LabelValue label="保险信息" :width="200" :value="selectedItem.bxxx" />
            <LabelValue label="住院天数" :width="160" :value="selectedItem.zyts" />
          </div>
          <div class="flex items-center">
            <LabelValue label="住院病区" :width="160" :value="selectedItem.wardName" />
            <LabelValue label="入区时间" :width="220" :value="selectedItem.lastDeptRegTime" />
            <LabelValue label="账户余额" :width="200" :value="formatAmount(selectedItem?.yjje) + '元'" />
            <LabelValue label="入院诊断" :width="160" :value="selectedItem.ryzd" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-hidden" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <div class="flex justify-between mt-2">
            <a-form class="form-style-flex flex mt-2">
              <a-form-item label="" class="w-72">
                <a-input v-model:value="formState.keyword" :disabled="listLoading" allow-clear placeholder="项目名称/助记码" @keyup.enter="onSearchList" />
              </a-form-item>
              <a-form-item label="申请日期" class="w-72 ml-4">
                <a-range-picker
                  v-model:value="formState.rangeDate"
                  :disabled="listLoading"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="onSearchList"
                />
              </a-form-item>
              <a-form-item label="仅看未执行医嘱" class="ml-4">
                <a-switch v-model:checked="formState.execNurseStatus" class="ml-2" un-checked-value="" :checked-value="0" @change="onSearchList" />
              </a-form-item>
              <a-form-item v-if="!isShowAllAdvice" label="查看所有医嘱" class="ml-4">
                <a-switch v-model:checked="formState.showAllAdvice" class="ml-2" @change="onSearchList" />
              </a-form-item>
            </a-form>
            <a-space>
              <a-button type="primary" :disabled="!selectedRowKeys.length" @click="onActionAll">批量执行</a-button>
              <!-- <a-button type="primary" :disabled="!!selectedRowKeys.length">批量撤销</a-button> -->
            </a-space>
          </div>
          <!-- 000105 -->
          <BaseTable
            fill
            class="mt-2"
            row-key="id"
            :loading="loading"
            column-code="00001083"
            :scroll="{ x: 2100 }"
            :data-source="tableData"
            :pagination="pagination"
            :exclude-columns="isShowAllAdvice ? ['execEmpName'] : []"
            :row-selection="{
              selectedRowKeys,
              onChange: onSelectChange,
              getCheckboxProps: (record) => ({
                disabled:
                  record.execNurseStatus !== 0 ||
                  record.execStatus === 4 ||
                  record.execStatus === 3 ||
                  (!isShowAllAdvice && record.ksdm && userStore.ksdm !== record.ksdm)
              })
            }"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'execStatus'">
                <!-- execStatus：执行状态  0：待执行(非药品)在此为已申请 1：已执行 2：待执行（已发药）非药品在此为已申请3：已退药 4：退药中   -->
                <!-- <a-tag v-if="record.execStatus === 0" color="blue">
                  <span v-if="!record.ksdm || record.ksdm === userStore.ksdm">已申请</span>
                  <span v-else>{{ isShowAllAdvice ? '已执行' : '已申请' }}</span>
                </a-tag>
                <a-tag v-if="record.execStatus === 1" color="blue">
                  <span v-if="!record.ksdm || record.ksdm === userStore.ksdm">已执行</span>
                  <span v-else>{{ isShowAllAdvice ? '已申请' : '已执行' }}</span>
                </a-tag> -->
                <a-tag v-if="record.execStatus === 0" color="blue">已申请</a-tag>
                <a-tag v-if="record.execStatus === 1" color="success">已执行</a-tag>
                <a-tag v-if="record.execStatus === 2" color="blue">{{ isDrug(record.advTypeCode) ? '已发药' : '已申请' }}</a-tag>
                <a-tag v-if="record.execStatus === 3" color="green">已退药</a-tag>
                <a-tag v-if="record.execStatus === 4" color="red">退药中</a-tag>
              </template>
              <template v-if="column.dataIndex === 'execNurseStatus'">
                <a-tag v-if="record.execNurseStatus === 0" color="blue">未执行</a-tag>
                <a-tag v-if="record.execNurseStatus === 1" color="success">已执行</a-tag>
              </template>
              <template v-if="column.dataIndex === 'execEmpName'">
                <span v-if="!record.ksdm || userStore.ksdm === record.ksdm">-</span>
                <span v-else>{{ record.execEmpName || '-' }}</span>
              </template>
              <template v-if="column.dataIndex === 'children'">
                <!-- sl: 'clinicalDose',
                dw: 'adv.jldw', -->
                <DoctorAdviceOrder
                  :row-data="record"
                  :params-key="{
                    mc: 'adv.mc',
                    gg: 'adv.gg',
                    sl: 'count',
                    dw: 'countUnit',
                    yf: 'deliverRoute.fyff',
                    pl: 'fqy.plid',
                    drugPathName: 'drugPathName'
                  }"
                />
              </template>

              <div v-if="column.dataIndex === 'yzzxlb'">
                {{ record.yzzxlb == 0 ? '临时' : '长期' }}
              </div>
              <!-- && isShowAllAdvice -->
              <template
                v-if="
                  column.dataIndex === 'action' &&
                  (isShowAllAdvice || (!isShowAllAdvice && userStore.ksdm === record.ksdm) || (!isShowAllAdvice && !record.ksdm))
                "
              >
                <!-- <a-button v-if="record.execStatus === 0 || record.execStatus === 2" type="link" size="small" @click="onAction([record.id], 1)">执行</a-button>
                <ConfirmModal v-if="record.execStatus === 1" description="确定撤销执行吗？" @confirm="onAction([record.id], 2)">
                  <a-button type="text" danger size="small">撤销执行</a-button>
                </ConfirmModal> -->
                <a-button
                  v-if="record.execNurseStatus === 0 && (record.execStatus === 0 || record.execStatus === 2)"
                  type="link"
                  size="small"
                  @click="onAction([record.id], 1)"
                  >执行</a-button
                >
                <ConfirmModal v-if="record.execNurseStatus === 1" description="确定撤销执行吗？" @confirm="onAction([record.id], 2)">
                  <a-button type="text" danger size="small">撤销执行</a-button>
                </ConfirmModal>
                <ConfirmModal v-if="record.execStatus === 2 && isDrug(record.advTypeCode)" description="确定退药吗？" @confirm="onDrugStatus(record, 0)">
                  <a-button type="text" danger size="small">退药</a-button>
                </ConfirmModal>

                <!-- (record.execStatus === 2 && !isDrug(record.advTypeCode)) ||
                    record.execNurseStatus === 0 -->
                <a-button v-if="record.execStatus === 0 || record.execStatus === 3" type="text" danger size="small" @click="openCancelModal(record)"
                  >撤销申请</a-button
                >
                <ConfirmModal
                  v-if="record.execStatus === 4 && isDrug(record.advTypeCode)"
                  danger
                  description="确定撤销退药吗？"
                  @confirm="onDrugStatus(record, 1)"
                >
                  <a-button type="text" danger size="small">撤销退药</a-button>
                </ConfirmModal>
              </template>
            </template>
          </BaseTable>
        </a-card>
      </div>
    </div>
    <CancelModal v-model:open="cancelOpen" :row-data="rowData" @success="onSuccess" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { debounce } from 'lodash-es'
import BaseTable from '@/components/BaseTable'
import ConfirmModal from '@/components/ConfirmModal'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import PatientListDrawer from '@/components/business/PatientListDrawer'
import LabelValue from '@/components/LabelValue'
import { formatAmount } from '@/utils/format'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import CancelModal from './CancelModal.vue'

const userStore = useUserStore()
const selectedRowKeys = ref([])
// const executed = ref(0)
// const unexecuted = ref(0)
// const ytysl = ref(0)
const patientList = ref([])
const selectedItem = ref({})
const formState = ref({
  keyword: '',
  execNurseStatus: 0,
  showAllAdvice: false,
  rangeDate: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const cancelOpen = ref(false)
const listLoading = ref(true)
const rowData = ref({})
const { tableData, getData, pagination, loading } = useTable({
  url: '/inp/clinicalOrder/getClinicalOrderExecuteList',
  immediate: false,
  formatParams: () => {
    return {
      inplsh: selectedItem.value.inplsh,
      ...formState.value,
      // execStatus: formState.value.execNurseStatus,
      showAllAdvice: isShowAllAdvice ? true : formState.value.showAllAdvice,
      startTime: formState.value.rangeDate?.[0] || '',
      endTime: formState.value.rangeDate?.[1] || ''
    }
  }
})
const onSearchList = () => {
  if (!selectedItem.value.inplsh) return
  getData()
}
const searchParams = ref({
  bqid: '',
  zjm: ''
})

const onSearch = debounce(() => getInpRecordList(), 300)

// 获取左侧患者列表
const getInpRecordList = async () => {
  listLoading.value = true
  selectedItem.value = {}
  const { code, data, msg } = await post('/inp/inpComprehensive/getInpRecordInfo', { bqid: searchParams.value.bqid, zjm: searchParams.value.zjm })
  listLoading.value = false
  if (code !== 0) return message.error(msg)
  patientList.value = data
  if (data[0]) {
    selectedItem.value = data[0]
    // getExecuteCount()
    getData()
  }
}

// 获取执行数量
// const getExecuteCount = async () => {
//   const { code, data, msg } = await post('/inp/clinicalOrder/getClinicalOrderExecuteListCount', {
//     inplsh: selectedItem.value.inplsh
//   })
//   if (code !== 0) return message.error(msg)
//   executed.value = data.wzxCount
//   unexecuted.value = data.yzxCount
//   ytysl.value = data.ytysl
//   getData()
// }

const selectPatient = (patient) => {
  selectedItem.value = patient
  // getExecuteCount()
  getData()
}

// 获取包括子医嘱的id
const extractIds = (data) => {
  return data.reduce((ids, item) => {
    if (item.id !== undefined) {
      ids.push(item.id)
    }
    if (item.children) {
      ids.push(...extractIds(item.children))
    }
    return ids
  }, [])
}
//执行
const onAction = async (ids, execStatus) => {
  const selectArr = tableData.value.filter((value) => ids.includes(value.id))
  const arrId = extractIds(selectArr)
  const res = await post('/inp/clinicalOrder/doNurseExecuteClinicalOrder', {
    zxyzids: arrId,
    execStatus,
    execNurseStatus: execStatus === 1 ? execStatus : 0
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success('操作成功')
  selectedRowKeys.value = []
  // getExecuteCount()
  getData()
}
//多选执行
const onActionAll = () => {
  onAction(selectedRowKeys.value, 1)
}
const onSelectChange = (keys) => {
  selectedRowKeys.value = keys
}
const onDrugStatus = async (record, status) => {
  // 退药
  if (status === 0) {
    const res = await post('/inp/zyhs/nurseReturnsMedicine', {
      id: record.id
    })
    if (res.code !== 0) return message.error(res.msg || '操作失败')
    message.success('操作成功')
  } else {
    //撤销退药
    const res = await post('/inp/zyhs/nurseQuashReturnsMedicine', {
      id: record.id
    })
    if (res.code !== 0) return message.error(res.msg || '操作失败')
    message.success('操作成功')
  }
  // getExecuteCount()
  getData()
}
const onSuccess = () => {
  getData()
}
const openCancelModal = (record) => {
  rowData.value = record
  cancelOpen.value = true
}
const isDrug = (code) => {
  // advTypeCode  2,4,5为药品别的为非药品
  if (code === 2 || code === 4 || code === 5) {
    return true
  } else {
    return false
  }
}
watch(
  () => selectedItem.value.inplsh,
  () => {
    formState.value = {
      keyword: '',
      execNurseStatus: 0,
      rangeDate: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    }
  },
  { immediate: true }
)
const isShowAllAdvice = getSystemConfig('INP_NURSE_EXECUTE_ALL_ADVICE') === '0'

onMounted(() => {
  getInpRecordList()
})
</script>
<style lang="less" scoped>
.bg-color {
  background: var(--thin-color);
}
:deep(.ant-table-row-expand-icon) {
  display: none;
}
.classify-checkall {
  .ant-tag {
    font-size: 14px;
    line-height: 30px;
    padding-inline: 14px;
  }
}
</style>
